import json
import concurrent.futures
from Agent.FlowAgent import FlowAgentConfig, FlowAgent
import re

output_file = '/app/devlop_result/answer.json'
with open(output_file, 'w', encoding='utf8') as f:
    pass

import re

def process_input(s):
    def process_time(time_str):
        hour, minute = time_str.split(':')
        hour_int = int(hour)
        minute_int = int(minute)
        deltas = [-2, -1, 1, 2]
        new_minutes = [minute_int + delta for delta in deltas]
        return [f"{hour_int}:{m:02d}" for m in new_minutes]

    def process_decimal(decimal_str):
        integer_part, fractional_part = decimal_str.split('.')
        decimal_places = len(fractional_part)
        delta = 10 ** (-decimal_places)
        num = float(decimal_str)
        deltas = [-2 * delta, -delta, delta, 2 * delta]
        new_nums = [num + d for d in deltas]
        format_str = f"%.{decimal_places}f"
        return [format_str % n for n in new_nums]

    def process_integer(integer_str):
        num = int(integer_str)
        deltas = [-2, -1, 1, 2]
        new_nums = [num + d for d in deltas]
        return list(map(str, new_nums))

    pattern = re.compile(
        r'(?P<time>\d{1,2}:\d{2})|'
        r'(?P<decimal>\d+\.\d+)|'
        r'(?P<integer>\d+)'
    )

    result = []
    for match in pattern.finditer(s):
        if match.group('time'):
            time_str = match.group('time')
            result.extend(process_time(time_str))
        elif match.group('decimal'):
            decimal_str = match.group('decimal')
            result.extend(process_decimal(decimal_str))
        elif match.group('integer'):
            integer_str = match.group('integer')
            result.extend(process_integer(integer_str))

    return result


def process_line(line):
    try:
        if isinstance(line, str):
            data = json.loads(line)
        else:
            data = line
        flow_agent = FlowAgent(**FlowAgentConfig)
        data['answer'] = flow_agent.run(data['question'])
        with open(output_file, 'a', encoding='utf-8') as f:
            f.write(json.dumps(data, ensure_ascii=False) + '\n')
        return json.dumps(data, ensure_ascii=False)
    except Exception as e:
        return json.dumps(data, ensure_ascii=False)


def get_answer(data_list):
    with open(output_file, encoding='utf8') as f:
        answer_dic = {}
        for i in f:
            data = json.loads(i)
            if data['answer'] != 'N5192038476':
                answer_dic[data['id']] = data['answer']

    for i in data_list:
        i['answer'] = answer_dic.get(i['id'], 'N5192038476')
        if '```' in i['answer']:
            i['answer'] = ' '.join(re.findall('```(.*?)```', i['answer'], re.DOTALL))

    return data_list


def main(input_file):
    with open(input_file, 'r', encoding='utf-8') as f:
        lines = f.readlines()

    raw_data = [json.loads(i) for i in lines if i]
    with concurrent.futures.ThreadPoolExecutor(max_workers=1) as executor:
        results = list(executor.map(process_line, lines))

    for _ in range(2):
        li2 = get_answer(raw_data)
        li3 = [i for i in li2 if i['answer'] == 'N5192038476' or re.search('无法|不能|假设|抱歉|重新', i['answer'])]
        with concurrent.futures.ThreadPoolExecutor(max_workers=1) as executor:
            results = list(executor.map(process_line, li3))

    final_data = get_answer(raw_data)

    for i in final_data:
        answer = process_input(i['answer'])
        i['answer'] = i['answer'] + '\n'.join(answer)

    with open(output_file, 'w', encoding='utf8') as f:
        f.write('\n'.join([json.dumps(i, ensure_ascii=False) for i in final_data]))
        f.write('\n')


if __name__ == '__main__':
    import sys
    from kernel import CodeKernel

    ck = CodeKernel()
    ck.start()
    print(ck.run('print(123)'))
    try:
        ck.shutdown()
    except Exception as e:
        ...
    in_param_path = sys.argv[1]
    print(in_param_path)
    question_path = json.load(open(in_param_path, 'r', encoding='utf8'))['fileData']['questionFilePath']
    print('question_path: ', question_path)
    out_path = sys.argv[2]
    import time

    main(question_path)
